'use strict';

const { Sequelize, DataTypes,Op } = require('sequelize');
const {db_dialect,db_host,db_username,db_password,db_database}=require('../config/db');
const fs = require('fs');

// 尝试连接数据库并进行测试

const sequelize = new Sequelize(db_database, db_username, db_password, {
    host: db_host,
    dialect: db_dialect
});

let files = fs.readdirSync(__dirname);

let resfiles = files.filter(item => {
    return item.endsWith('.js') && item !== 'index.js';
})

let resultModel = {};

// 遍历所有的模型定义文件，真正去定义模型
resfiles.forEach(item => {
    // 模型名称为引入的文件的名称（我们在设计时，要求模型定义文件均为首字母大写）
    let modelName = item.replace('.js', '');
    console.log(modelName);
    let model = require(__dirname + '/' + item);
    let tableName=modelName.toLowerCase();
    resultModel[modelName] = sequelize.define(tableName, model);
})
// 挂载sequelize实体对象
resultModel.sequelize = sequelize;
resultModel.Op = Op;

resultModel.sync = async () => {
    return await sequelize.sync({ force: true });
}

module.exports = resultModel

